package com.wltt.product.ahuthr.config.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wltt.product.ahuthr.component.SystemUserComponent;
import com.wltt.product.ahuthr.config.exception.BusinessException;
import com.wltt.product.ahuthr.enums.SystemUserStatusEnum;
import com.wltt.product.ahuthr.holder.UserHolder;
import com.wltt.product.ahuthr.model.ResultData;
import com.wltt.product.ahuthr.model.po.CurrentUserInfoBO;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;

import java.io.IOException;
import java.io.PrintWriter;

public class AuthFilter implements Filter {

    private SystemUserComponent systemUserComponent;

    private String[] excludePaths;

    public AuthFilter(SystemUserComponent systemUserComponent) {
        this.systemUserComponent = systemUserComponent;
    }


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String param = filterConfig.getInitParameter("excludePaths");
        if (null != param && !"".equals(param)) {
            this.excludePaths = param.split(",");
        }

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 开放接口直接跳过
        String requestURI = request.getRequestURI();
        if (isExcludePath(requestURI)) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            CurrentUserInfoBO currentUserInfoBO = systemUserComponent.loginUserInfo(request);
            if (currentUserInfoBO == null) {
                doErrorReturn(response, HttpStatus.UNAUTHORIZED.value(), "登录认证失败");
                return;
            }
            if (SystemUserStatusEnum.RETESTED.getCode() == currentUserInfoBO.getUserStatus()
                    || SystemUserStatusEnum.UNACTIVATED.getCode() == currentUserInfoBO.getUserStatus()) {
                doErrorReturn(response, HttpStatus.NOT_ACCEPTABLE.value(), "账户需要激活");
                return;
            }
            UserHolder.setUser(currentUserInfoBO);
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    /**
     * 权限不足返回
     *
     * @param response
     * @return
     */
    private void doErrorReturn(HttpServletResponse response,
                               int respCode,
                               String respDesc) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setStatus(respCode);
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        try {
            ResultData resultData = ResultData.failure(respCode, respDesc);
            writer.write(new ObjectMapper().writeValueAsString(resultData));
            writer.flush();
        } finally {
            writer.close();
        }
    }

    /**
     * 判断是否是排除项
     *
     * @param requestURI
     * @return
     */
    private boolean isExcludePath(String requestURI) {
        for (String excludePath : excludePaths) {
            if (requestURI.startsWith(excludePath)) {
                return true;
            }
        }
        return false;
    }
}
